// Jpg2Bgr.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "Jpg2Bgr.h"
#ifdef _DEBUG
#include <opencv2\opencv.hpp>
#include <iostream>
#include <fstream>
#endif
extern "C" {
#include <stdio.h>
#include <jpeglib.h>
#include <setjmp.h>
}

int Jpg2BGR(unsigned char* pJpgBuffer, int nJpgLen, unsigned char** pBgrBuffer, int *nBgrLen){
	if (pJpgBuffer[0] != (unsigned char)0xff || pJpgBuffer[1] != (unsigned char)0xd8 || pJpgBuffer[nJpgLen - 2] != (unsigned char)0xff || pJpgBuffer[nJpgLen - 1] != (unsigned char)0xd9){
		return -400;
	}
	struct jpeg_decompress_struct cinfo;  
	struct jpeg_error_mgr jerr;
	cinfo.err = jpeg_std_error(&jerr);
	jpeg_create_decompress(&cinfo);
	jpeg_mem_src(&cinfo, pJpgBuffer, nJpgLen);
	jpeg_read_header(&cinfo, TRUE);
	if (cinfo.num_components != 3){
		jpeg_destroy_decompress(&cinfo);
		return -401;
	}
	*nBgrLen = cinfo.image_width*cinfo.image_height*cinfo.num_components;
	jpeg_start_decompress(&cinfo);
	JSAMPROW row_pointer[1];
	while (cinfo.output_scanline < cinfo.output_height)
	{
		row_pointer[0] = &(*pBgrBuffer)[cinfo.output_scanline*cinfo.image_width*cinfo.num_components];
		jpeg_read_scanlines(&cinfo,row_pointer,1);
	}
	jpeg_finish_decompress(&cinfo);
	jpeg_destroy_decompress(&cinfo);
	return 0;
}

#ifdef _DEBUG
int _tmain(int argc, _TCHAR* argv[])
{
	std::ifstream in;
	in.open("D:\\master\\master_traindata\\jpg2bgr\\t.jpg", std::ios::in | std::ios::binary);
	char bytes[13516];
	unsigned char *bgr = new unsigned char[1024000];
	int bgrSize,jpgSize,width = 595,height=300;
	//in.read(bytes, 13516);
	in.seekg(0, std::ios::end);
	jpgSize = in.tellg();
	in.seekg(0, std::ios::beg);
	//bytes = new char[jpgSize];
	/*
	for (int i = 0; i < jpgSize;i++){
		in >> bytes[i];
	}*/
	in.read(bytes,jpgSize);
	cv::Mat mat;
	mat.create(cv::Size(width,height),CV_8UC3);
	clock_t tik = clock();
	Jpg2BGR((unsigned char*)bytes,13516,&bgr,&bgrSize);
	clock_t tok = clock();
	std::cout << "tok - tik = " << tok - tik << std::endl;
	memcpy_s(mat.data, bgrSize, bgr, bgrSize);
	imshow("1",mat);
	cv::waitKey(0);
	std::cin >> bgrSize;
	in.close();
	return 0;
}
#endif
